package route

import (
	"context"
	"database/sql"
	"demo_system/fronted/middleware"
	"demo_system/fronted/web/controllers"
	"demo_system/lib/validation"
	"demo_system/repositories"
	"demo_system/services"
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
)

type Router struct {
	app *iris.Application
	db  *sql.DB
	ctx context.Context
}

func NewRouter(app *iris.Application, db *sql.DB, ctx context.Context) *Router {

	return &Router{app, db, ctx}
}

//注册前端路由
func (r *Router) RegRouter() {
	//设置下默认的页面
	r.app.Get("/", func(ctx iris.Context) {
		ctx.Redirect("/user/login")
	})


	//user 实例化model层
	userRepository := repositories.NewUserRepository(r.db)
	userService := services.NewService(userRepository)

	myValid := validation.NewFrontValidator()
	myValid.RegCustomTag()
	dependencies := make([]interface{}, 0)
	dependencies = append(dependencies, r.ctx, userService, myValid)               //组装成一个依赖切片
	r.bindRouteAndRegDependencies("/user", new(controllers.UserController), dependencies) //绑定路由并注册依赖
}

func (r *Router) bindRouteAndRegDependencies(url string, controller interface{}, dependencies []interface{}) {
	party := r.app.Party(url)
	party.Use(middleware.AuthLogin)
	partyApp := mvc.New(party)
	partyApp.Register(dependencies...) //注册控制器所需依赖
	partyApp.Handle(controller)
}
